import 'dart:developer';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/home/news_item_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/base/wqs_image.dart';
import 'package:ball_lion/widgets/focus_button.dart';
import 'package:ball_lion/widgets/html/wqs_html.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/player/qs_player_logic.dart';

class NewsDetailView extends StatefulWidget {
  final NewsItemEntity? data;
  final String? id;
  const NewsDetailView({this.data, this.id, super.key});

  @override
  State<NewsDetailView> createState() => _NewsDetailViewState();
}

class _NewsDetailViewState extends State<NewsDetailView> {
  late final QsPlayerLogic logic;

  @override
  void initState() {
    logic = Get.put(QsPlayerLogic(autoPlay: false), tag: "${widget.data?.id}");
    super.initState();
  }

  @override
  void dispose() {
    logic.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(bottom: 20),
      decoration: const BoxDecoration(
        color: Colours.white,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: 14),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: QsText(widget.data?.title ?? '',
                fontSize: 22, fontWeight: FontWeight.w500),
          ),
          const SizedBox(height: 8),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: QsText(widget.data?.publishTime ?? '',
                color: Colours.N7, fontSize: 12),
          ),
          const SizedBox(height: 16),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Row(
              children: [
                GestureDetector(
                  // onTap: () {
                  //   Utils.onEvent("zxxq", params: {"zxxq": 2});
                  //   Get.toNamed(Routes.userPage,
                  //       arguments: widget.data?.publisherId,
                  //       parameters: {'type': '1'});
                  // },
                  child: Row(children: [
                    ClipOval(
                        child: CachedNetworkImage(
                      imageUrl: widget.data?.logo ?? '',
                      width: 40,
                      height: 40,
                      fit: BoxFit.cover,
                    )),
                    const SizedBox(width: 8),
                    QsText(widget.data?.publisherName ?? ''),
                  ]),
                ),
                const Spacer(),
                FocusButton(
                  widget.data?.focus ?? 0,
                  userId: widget.data?.publisherId,
                  onTap: (p0) => Utils.onEvent("article_follow", params: {
                    "article_id": widget.data?.id,
                    "follow": p0,
                    "channel": widget.id
                  }),
                )
              ],
            ),
          ),
          Container(height: 16),
          QsHtml(
            data: widget.data?.content ?? "",
            id: widget.data?.id ?? 0,
            player: logic,
            disclaimer: widget.data?.disclaimer,
            matchLabel: widget.data?.hrefList,
            mediaFrom: widget.data?.media,
            showFeeLine: true,
          )
        ],
      ),
    );
  }

  String getData() {
    var regC = RegExp(r"[\u4e00-\u9fa5]");
    var regCom = RegExp(r'<\/p>[.\n\s]*<p>');
    var regP = RegExp(r'\/>[.\n\s]*<p>');
    var regImg = RegExp(r'\/>[.\n\s]*<img');
    var regInLine = RegExp(r'<p[^<>]*>[^<>]+<img');
    String append = '';
    String? com =
        widget.data?.content?.splitMapJoin(regInLine, onMatch: (match) {
      var result = match[0]?.split("<img").join("</p><p><img") ?? "";
      return result;
    });
    // .split(RegExp(r"<[br \/]+>")).join("")
    com = com?.replaceAllMapped(
        RegExp(r"<div\s.*?>([\s\S]*?)<\/div>"), (match) => match.group(1)!);
    com = com?.replaceAllMapped(RegExp(r"""<span class="img">(.*?)<\/span>"""),
        (match) => match.group(1)!);
    com = com
            ?.split("<p>&nbsp;</p>")
            .join("<div style= 'height: 8;width: 200px;'>  </div>")
            .split(regCom)
            .join("</p><div style= 'height: 8;width: 200px;'>  </div><p>")
            .split(regP)
            .join("/><div style= 'height: 8;width: 200px;'>  </div><p>")
            .split(regImg)
            .join("/><div style= 'height: 8;width: 200px;'>  </div><img")
            .split('src=" ')
            .join('src="')
        // .split(regBody)
        // .join("/p><div style= 'height: 25;width: 200px;'>  </div></body")
        ??
        "";
    log(com);
    com.split("").forEach((element) {
      if (regC.hasMatch(element)) {
        append += "$element\u200A";
      } else {
        append += element;
      }
    });

    var newData = "";
    newData = "<body id='wholeBody'>"
        "<div id='article'>$append</div>"
        "<div style= 'height: 24px;width: 200px;'>  </div>"
        "${widget.data?.hrefList == null ? "" : "<matchLabel> </matchLabel>"}"
        "${widget.data?.media == null || widget.data?.media == '' ? '' : "<p id='reprint'>${'转\u200A载\u200A自\u200A：\u200A${widget.data?.media?.split('').join("\u200A")}'}</p>"}"
        "<p id='claim'>${widget.data?.disclaimer?.split('').join("\u200A") ?? ''}</p>"
        "</body>";
    return newData;
  }

  Widget labelCell(HrefItem item) {
    Widget cell = Container();
    switch (item.type) {
      case 1:
        List<String> name = item.name?.split(",") ?? [];
        List<String> logo = item.logo?.split(",") ?? [];
        cell = Row(
          mainAxisSize: MainAxisSize.min,
          children: List.generate(
              2,
              (index) => infoCell(
                  logo.length - 1 < index ? "" : logo[index],
                  name.length - 1 < index ? "" : name[index],
                  index == 1)).insertWith(1, [
            Image.asset(width: 16, Utils.getImgPath("news_vs.png"))
                .paddingSymmetric(horizontal: 6)
          ]),
        );
        break;
      default:
        cell = infoCell(item.logo, item.name, false);
    }
    return GestureDetector(
      onTap: () {
        switch (item.type) {
          case 1:
            Get.toNamed(Routes.zqMatchDetail, arguments: item.extId);
            break;
          case 2:
            Get.toNamed(Routes.leagueDetail,
                arguments: item.extId.toString(),
                parameters: {"type": "0", "index": "0"});
            break;
          case 3:
            Get.toNamed(Routes.zqTeamDetail, arguments: item.extId);
            break;
        }
      },
      child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          decoration: BoxDecoration(
              color: Colours.greyF7, borderRadius: BorderRadius.circular(4)),
          child: cell),
    );
  }

  Widget infoCell(String? logo, String? name, bool reverse) {
    List<Widget> list = [
      QsImage(imageUrl: logo, width: 16, height: 16),
      Container(width: 4),
      QsText(name ?? "", fontSize: 12)
    ];
    if (reverse) list = list.reversed.toList();
    return Row(mainAxisSize: MainAxisSize.min, children: list);
  }
}
